package com.xhwl.centiotdata.handler.account.impl;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.account.AccountFactory;
import com.xhwl.centiotdata.handler.account.AccountHandler;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationFactory;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.IAuthAccountCentService;
import com.xhwl.centiotdata.service.cent.IPedestrianCentService;
import com.xhwl.common.dto.auth.PedestrianAuthDTO;
import com.xhwl.common.dto.cent.sdata.AccountDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.enums.SourceTypeEnum;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.pojo.cent.auth.CardInfo;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.pojo.cent.sdata.personnel.StaffDTO;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.common.vo.cent.auth.CardOfUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangyiling
 * @description 大华ICC
 * @date 2022/7/5 10:31
 */
@Slf4j
@Service
public class AccountDaHuaIccHandler extends AccountHandler {
    @Resource
    private IAuthAccountCentService iAuthPedestrianCentService;

    @Autowired
    private IPedestrianCentService pedestrianCentService;

    @Override
    public void add(StaffDTO dto, Integer projectId, DeviceProjSupplierCategory integrationConfig) {
        handleAdd(dto, projectId, integrationConfig);
    }

    private void handleAdd(StaffDTO staffDTO, Integer projectId, DeviceProjSupplierCategory integrationConfig) {
        if (null != integrationConfig) {
            try {
                JSONObject properties = integrationConfig.getProperties();
                Integer productId = integrationConfig.getProductId();
                PedestrianAuthDTO pedestrianAuthDTO = handleCommonInfo(staffDTO, projectId, productId);
                pedestrianAuthDTO.setProjectId(projectId);
                pedestrianAuthDTO.setProductId(productId);
                PedestrianIntegrationConfigDTO config = new PedestrianIntegrationConfigDTO();
                config.setIpAndPort(properties.getString("ipAndPort"));
                config.setAk(properties.getString("ak"));
                config.setSk(properties.getString("sk"));
                config.setProductId(productId);
                config.setLoginName(properties.getString("loginName"));
                config.setPassword(properties.getString("password"));
                config.setProjectId(projectId);
                PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(productId);
                if (handler != null) {
                    //卡号同步到第三方时 需要转换
                    List<String> originCard = pedestrianAuthDTO.getCardNumberList();
                    List<String> cardNumberList = pedestrianAuthDTO.getCardNumberList();
                    Map<Integer, Map<String, String>> carNumberMap = new HashMap<>();
                    if (!org.springframework.util.CollectionUtils.isEmpty(cardNumberList)) {
                        carNumberMap = pedestrianCentService.cardTransition(pedestrianAuthDTO.getProjectId(), cardNumberList);
                    }
                    Map<String, String> carMap = carNumberMap.get(config.getProductId());
                    if (!CollectionUtils.isEmpty(carMap)) {
                        pedestrianAuthDTO.setCardNumber(carMap.get(pedestrianAuthDTO.getCardNumber()));
                        pedestrianAuthDTO.setCardNumberList(new ArrayList<>(carMap.values()));
                    }
                    handler.addUser(config, pedestrianAuthDTO);
                    pedestrianAuthDTO.setIndustryId(staffDTO.getIndustryId());
                    pedestrianAuthDTO.setCategoryId(CategoryEnum.DOOR.getId());
                    pedestrianAuthDTO.setSourceType(SourceTypeEnum.USER.type);
                    pedestrianAuthDTO.setCardNumber(originCard.get(0));
                    pedestrianAuthDTO.setCardNumberList(originCard);
                    log.error("--添加人员---config==" + config + "-----pedestrianAuthDTO==" + pedestrianAuthDTO);
                    iAuthPedestrianCentService.saveCardOnly(pedestrianAuthDTO);
                }
            } catch (Exception e) {
                log.error("账号信息：{}", staffDTO);
                log.error("配置信息：{}", integrationConfig);
                log.error("同步大华icc异常", e);
            }
        }
    }

    @Override
    public void update(StaffDTO staffDTO, Integer projectId, DeviceProjSupplierCategory integrationConfig) {
        //查询关联表
        AuthAccountMapping authAccount = iAuthPedestrianCentService.query(projectId, staffDTO.getAccountId(), integrationConfig.getProductId());
        //没查到关联关系，则新增
        if (null == authAccount) {
            handleAdd(staffDTO, projectId, integrationConfig);
        }
    }

    @Override
    public void delete(AccountDTO accountDTO, Integer projectId, DeviceProjSupplierCategory integrationConfig) {
        if (null != integrationConfig) {
            //查询关联表
            AuthAccountMapping authAccount = iAuthPedestrianCentService.query(projectId, accountDTO.getId(), integrationConfig.getProductId());
            if (null != authAccount) {
                handleDelete(authAccount, projectId, integrationConfig);
                iAuthPedestrianCentService.deleteAccountMapping(projectId, accountDTO.getId(), authAccount.getOpenId(), integrationConfig.getProductId());
                //删除卡号
                iAuthPedestrianCentService.deleteByAccount(accountDTO.getId());
            }
        }
    }

    private void handleDelete(AuthAccountMapping authAccount, Integer projectId, DeviceProjSupplierCategory integrationConfig) {
        try {
            JSONObject properties = integrationConfig.getProperties();
            Integer productId = integrationConfig.getProductId();
            PedestrianAuthDTO pedestrianAuthDTO = new PedestrianAuthDTO();
            pedestrianAuthDTO.setProjectId(projectId);
            pedestrianAuthDTO.setProductId(productId);
            pedestrianAuthDTO.setSourceId(authAccount.getAccountId());
            pedestrianAuthDTO.setUserOpenId(authAccount.getOpenId());

            PedestrianIntegrationConfigDTO config = new PedestrianIntegrationConfigDTO();
            config.setIpAndPort(properties.getString("ipAndPort"));
            config.setAk(properties.getString("ak"));
            config.setSk(properties.getString("sk"));
            config.setProductId(productId);
            config.setLoginName(properties.getString("loginName"));
            config.setPassword(properties.getString("password"));
            config.setProjectId(projectId);
            PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(productId);
            if (handler != null) {
                handler.deleteAuth(config, pedestrianAuthDTO);
            }
        } catch (Exception e) {
            log.error("账号信息：{}", authAccount);
            log.error("配置信息：{}", integrationConfig);
            log.error("同步海康平台异常", e);
        }
    }


    private PedestrianAuthDTO handleCommonInfo(StaffDTO staffDTO, Integer projectId, Integer productId) {
        PedestrianAuthDTO pedestrianAuthDTO = new PedestrianAuthDTO();
        if (StringUtils.isNotEmpty(staffDTO.getFaceUrl())) {
            pedestrianAuthDTO.setFaceUrl(staffDTO.getFaceUrl());
        }
        pedestrianAuthDTO.setAccountName(staffDTO.getName());
        pedestrianAuthDTO.setPhone(staffDTO.getPhone());
        pedestrianAuthDTO.setSourceId(staffDTO.getAccountId());
        // 查询一下我们平台是否有卡号,有卡直接取
        CardOfUserVO cardOfUserVO = new CardOfUserVO();
        cardOfUserVO.setSize(20);
        cardOfUserVO.setCurrent(1);
        cardOfUserVO.setUserId(pedestrianAuthDTO.getSourceId());
        cardOfUserVO.setProjectId(pedestrianAuthDTO.getProjectId());
        List<CardInfo> infos = iAuthPedestrianCentService.getUserCardDetailByUserid(cardOfUserVO).getRecords();
        log.error("查询到的卡号信息：" + infos);
        if (!CollectionUtils.isEmpty(infos)) {
            List<String> cardNumberList = infos.stream().map(CardInfo::getNumber).collect(Collectors.toList());
            Map<Integer, Map<String, String>> carNumberMap = pedestrianCentService.cardTransition(pedestrianAuthDTO.getProjectId(), cardNumberList);
            Map<String, String> carMap = carNumberMap.get(productId);
            if (!CollectionUtils.isEmpty(carMap)) {
                pedestrianAuthDTO.setCardNumberList(new ArrayList<>(carMap.values()));
            }
            pedestrianAuthDTO.setCardNumber(new ArrayList<>(carMap.values()).get(0));
            log.error("转换后的卡号信息：" + pedestrianAuthDTO.getCardNumberList());
//        } else {
//            String cardNumber = getEight(staffDTO.getPhone());
//            pedestrianAuthDTO.setCardNumberList(Collections.singletonList(cardNumber));
//            pedestrianAuthDTO.setCardNumber(cardNumber);
        }
        pedestrianAuthDTO.setOrgIds(staffDTO.getOrgIds());
        return pedestrianAuthDTO;
    }

    private static String getEight(String str) {
        if (org.springframework.util.StringUtils.isEmpty(str)) {
            return "0000000000";
        }
        int length = str.length();
        if (length == 10) {
            return str;
        }
        if (length < 10) {
            StringBuilder strBuilder = new StringBuilder(str);
            for (int i = 0; i < 10 - length; i++) {
                strBuilder.insert(0, "0");
            }
            return strBuilder.toString();
        } else {
            return str.substring(str.length() - 10);
        }

    }

    @Override
    public void afterPropertiesSet() {
        AccountFactory.register(ProductEnum.DAHUA_ICC.getId(), this);
        log.info("大华icc管理注册成功");
    }

}
